﻿using System;
using System.Collections.Generic;
using System.Threading;
using Top.Api.Stream;
using Top.Api.Request;
using Top.Api.Response;

namespace Top.Api.Sync
{
    /// <summary>
    /// 方案
    /// </summary>
    public class Proposal
    {
        private const string API_URL = "http://gw.api.tbsandbox.com/router/rest";
        private const string APP_KEY = "1021355613";
        private const string APP_SECRET = "sandbox6431303a2eee41ae92aea0928";
        private const string SESSION_KEY = "610042936d72c5fc6ac70ff8e959db9d8391514f5ae76732074082787";

        private static DateTime lastSync;
        private static Dictionary<long, bool> taskIds = new Dictionary<long, bool>();

        public static void Main(string[] args)
        {
            Proposal.StartProposal3();
            Console.Read();
        }

        /// <summary>
        /// 方案一
        /// </summary>
        public static void StartProposal1()
        {
            ITopClient client = new AutoRetryTopClient(API_URL, APP_KEY, APP_SECRET, "json");
            TopApiService topApiService = new TopApiService(client);

            // 初始化三个月内订单
            DateTime end = DateTime.Now;
            DateTime start = end.AddMonths(-3);
            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                List<DateTime[]> dateList = DateTimeUtils.SplitTimeByDays(start, end, 1);
                foreach (DateTime[] dates in dateList)
                {
                    topApiService.SyncSoldTrades(dates[0], dates[1], SESSION_KEY);
                }
            });
            lastSync = end;

            // 定时获取增量订单
            new Timer(new TimerCallback(delegate(object sender)
            {
                DateTime _start = lastSync.AddMinutes(-10); // 加载上一次的同步时间，并退后10分钟
                DateTime _end = DateTime.Now;
                topApiService.SyncIncrementSoldTrades(_start, _end, SESSION_KEY);
                lastSync = _end; // 把本次更新时间保存到数据库
            }), null, 0L, 5 * 60 * 1000L);
        }

        /// <summary>
        /// 方案二
        /// </summary>
        public static void StartProposal2()
        {
            ITopClient client = new AutoRetryTopClient(API_URL, APP_KEY, APP_SECRET, "json");
            TopApiService topApiService = new TopApiService(client);

            // 初始化三个月内订单
            DateTime now = DateTime.Now;
            string start = now.AddMonths(-3).ToString("yyyyMMdd");
            string end = now.AddDays(-1).ToString("yyyyMMdd");
            long taskId = topApiService.AsyncSoldTrades(start, end, SESSION_KEY).Value;
            taskIds.Add(taskId, false);

            // 定时轮询检查异步任务状态
            new Timer(new TimerCallback(delegate(object sender)
            {
                Dictionary<long, bool>.Enumerator en = taskIds.GetEnumerator();
                while (en.MoveNext())
                {
                    if (!en.Current.Value)
                    {
                        string url = topApiService.GetTaskResultUrl(en.Current.Key);
                        if (url != null)
                        {
                            topApiService.DownloadAndProcess(url);
                            taskIds.Add(en.Current.Key, true);
                        }
                    }
                }
            }), null, 0L, 3 * 60 * 1000L);

            // 获取今天增量订单
            topApiService.SyncIncrementSoldTrades(DateTimeUtils.GetTodayStartTime(), now, SESSION_KEY);
            lastSync = now;

            // 定时获取增量订单
            new Timer(new TimerCallback(delegate(object sender)
            {
                DateTime _start = lastSync.AddMinutes(-10); // 加载上一次的同步时间，并退后10分钟
                DateTime _end = DateTime.Now;
                topApiService.SyncIncrementSoldTrades(_start, _end, SESSION_KEY);
                lastSync = _end; // 把本次更新时间保存到数据库
            }), null, 0L, 5 * 60 * 1000L);
        }

        /// <summary>
        /// 方案三
        /// </summary>
        public static void StartProposal3()
        {
            ITopClient client = new AutoRetryTopClient(API_URL, APP_KEY, APP_SECRET, "json");
            TopApiService topApiService = new TopApiService(client);

            // 启动主动通知监听器
            topApiService.PermitUser(SESSION_KEY);
            Configuration conf = new Configuration(APP_KEY, APP_SECRET, null);
            ITopCometStream stream = new TopCometStreamFactory(conf).GetInstance();
            stream.SetConnectionListener(new ConnectionLifeCycleListener());
            stream.SetMessageListener(new TopCometMessageListener(topApiService));
            stream.Start();

            // 初始化三个月内订单
            DateTime now = DateTime.Now;
            string start = now.AddMonths(-3).ToString("yyyyMMdd");
            string end = now.AddDays(-1).ToString("yyyyMMdd");
            topApiService.AsyncSoldTrades(start, end, SESSION_KEY);

            // 获取今天的增量订单
            topApiService.SyncIncrementSoldTrades(DateTimeUtils.GetTodayStartTime(), now, SESSION_KEY);
        }

        /// <summary>
        /// 我的方案
        /// </summary>
        public static void StartProposal4()
        {
            ITopClient client = new AutoRetryTopClient(API_URL, APP_KEY, APP_SECRET, "json");
            TopatsTradesSoldGetRequest req = new TopatsTradesSoldGetRequest();
            TopatsTradesSoldGetResponse response = client.Execute(req, SESSION_KEY);
        }
    }
}
